let gameInfo = {
    roomId: null,
    thisUserId: null,
    thatUserId: null,
    isWhite: true,
}

// 界面显示

function setScreenText(me) {
    let screen = document.querySelector('#screen');
    if(me) {
        screen.innerHTML = "轮到你落子啦！";
    } else {
        screen.innerHTML = "轮到对方落子啦！";
    }
}

// 初始化 webSocket
let webSocketUrl =  "ws://" + location.host + "/game";
let webSocket = new WebSocket(webSocketUrl);

webSocket.onopen = function() {
    console.log("连接游戏房间成功");
    
}

webSocket.onclose = function() {
    console.log("与游戏房间断开连接！");
    
}

webSocket.onerror = function() {
    console.log("连接出现异常");
    
}

window.onbeforeunload = function() {
    webSocket.close();
}

webSocket.onmessage = function(e) {
    console.log("处理游戏就绪");
    let resp = JSON.parse(e.data);
    console.log(resp);
    if(resp.status == 'gameReady') {
        let readyResponse = resp.data;
        gameInfo.roomId = readyResponse.roomId;
        gameInfo.thisUserId = readyResponse.thisUserId;
        gameInfo.thatUserId = readyResponse.thatUserId;
        gameInfo.isWhite = (readyResponse.whiteUser == gameInfo.thisUserId);
        console.log(gameInfo);
        // 初始化棋盘
        initGame();
        // 设置显示区域内容
        setScreenText(gameInfo.isWhite);
    } else if(resp.status == 'repeatConnection') {
        alert("检测到游戏多开！请使用其他账号登录！");
        location.replace("/login.html");
    } else if(resp.status == 'noLogin') {
        location.replace("/login.html");
    }
}

// 初始化游戏
function initGame() {
    // 先后手情况
    let me = gameInfo.isWhite;
    // 游戏是否结束
    let over = false;
    // 棋盘
    let chessBoard = [];
    // 初始化棋盘数组
    for(let i = 0; i < 15; i++) {
        chessBoard[i] = [];
        for(let j = 0; j < 15; j++) {
            chessBoard[i][j] = 0;
        }
    }

    // 绘制棋盘
    let chess = document.querySelector('#chess');
    let context = chess.getContext('2d');
    context.strokeStyle = "#BFBFBF";
    // 背景图片
    let logo = new Image();
    logo.src = "img/chessboard.jpg";
    logo.onload = function () {
        context.drawImage(logo, 0, 0, 450, 450);
        initChessBoard();
    }

    // 绘制棋盘网格
    function initChessBoard() {
        for (let i = 0; i < 15; i++) {
            context.moveTo(15 + i * 30, 15);
            context.lineTo(15 + i * 30, 430);
            context.stroke();
            context.moveTo(15, 15 + i * 30);
            context.lineTo(435, 15 + i * 30);
            context.stroke();
        }
    }

    // 绘制棋子
    function oneStep(i, j, isWhite) {
        context.beginPath();
        context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
        context.closePath();
        var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
        if (!isWhite) {
            gradient.addColorStop(0, "#0A0A0A");
            gradient.addColorStop(1, "#636766");
        } else {
            gradient.addColorStop(0, "#D1D1D1");
            gradient.addColorStop(1, "#F9F9F9");
        }
        context.fillStyle = gradient;
        context.fill();
    }

    // 添加点击事件
    chess.onclick = function(e) {
        if(over) {
            return;
        }
        if(!me) {
            return;
        }
        let x = e.offsetX;
        let y = e.offsetY;

        // 注意, 横坐标是列, 纵坐标是行
        let col = Math.floor(x / 30);
        let row = Math.floor(y / 30);
        if (chessBoard[row][col] == 0) {
            // 发送坐标给服务器, 服务器要返回结果
            send(row, col);

            // 绘制棋子
            // oneStep(col, row, gameInfo.isWhite);
            // chessBoard[row][col] = 1;
        }
    }

    function send(row, col) {
        let req = {
            message: 'putChess',
            userId: gameInfo.thisUserId,
            row: row,
            col: col
        }
        webSocket.send(JSON.stringify(req));
    }

    // 当游戏就绪后，就不再会有游戏就绪响应了
    // 因此，直接在 initGame 内部修改 onmessage 方法，让这个方法里面针对落子响应进行处理
    webSocket.onmessage = function(e) {
        let resp = JSON.parse(e.data);
        console.log(resp);
        let gameResponse = resp.data;

        if(resp.status == 'putChess' && gameResponse.row >= 0 && gameResponse.col >= 0) {
            console.log(gameInfo.thisUserId == gameResponse.userId);
            console.log(gameInfo.thatUserId == gameResponse.userId);
            if(gameInfo.thisUserId == gameResponse.userId) {
                // 是自己落的子，绘制自己颜色的子
                oneStep(gameResponse.col, gameResponse.row, gameInfo.isWhite);
            } else if(gameInfo.thatUserId == gameResponse.userId) {
                // 对手的子
                oneStep(gameResponse.col, gameResponse.row, !gameInfo.isWhite);
            } else {
                console.log("落子异常！");
                return;
            }
            // 标记此处有子
            chessBoard[gameResponse.row][gameResponse.col] = 1;
        }

        // 交换轮次
        me = !me;
        // 判定胜负
        let screenDiv = document.querySelector('#screen');
        if(gameResponse.winner != 0) {
            if(gameResponse.winner == gameInfo.thisUserId) {
                screenDiv.innerHTML = "恭喜你！你赢了！";
            } else if(gameResponse.winner == gameInfo.thatUserId) {
                screenDiv.innerHTML = "很遗憾！你输了..."
            } else if(gameResponse.winner == -1) {
                screenDiv.innerHTML = "平局";
            } else {
                console.log("字段错误！" + gameResponse.winner);
            }
            
            // 增加一个按钮，让玩家点击按钮后再返回到游戏大厅
            let backBtn = document.createElement('button');
            backBtn.innerHTML = '回到大厅';
            backBtn.onclick = function() {
                location.replace("/game_hall.html");
            }
            let fatherDiv = document.querySelector('.container>div');
            fatherDiv.appendChild(backBtn);
        } else {
            setScreenText(me);
        }
        
    }
}

